package cool.tianyou.blue.bird;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cool.tianyou.blue.bird.model.po.Session;
import cool.tianyou.blue.bird.model.po.Sms;
import lombok.SneakyThrows;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, "blue_bird", null, 2);
    }

    private static DatabaseHelper instance;


    private Map<String, Dao> maps = new HashMap<>();

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Session.class);
            TableUtils.createTable(connectionSource, Sms.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, Session.class, true);
            TableUtils.dropTable(connectionSource, Sms.class, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public synchronized Dao getDao(Class cls) throws SQLException {
        Dao dao = null;
        String className = cls.getSimpleName();
        if (maps.containsKey(className)) {
            dao = maps.get(className);
        }
        if (dao == null) {
            dao = super.getDao(cls);
            maps.put(className, dao);
        }
        return dao;
    }

    public void close() {
        super.close();
        for (String key : maps.keySet()) {
            Dao dao = maps.get(key);
            dao = null;
        }
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null) {
                    instance = new DatabaseHelper(context);
                }
            }
        }
        return instance;
    }

    @SneakyThrows
    public Integer saveSession(Sms sms) {
        Session session = new Session(null,sms.getNumber(),sms.getNumber()
                ,sms.getContent(), sms.getTag(), sms.getCategory(),sms.getReceiveTime(),0);

        Dao dao = this.getDao(Session.class);
        List sessions = dao.queryBuilder().where().eq("number", session.getNumber()).query();
        if (!sessions.isEmpty()) {
            Session dbSession = (Session) sessions.get(0);
            session.setId(dbSession.getId());
            dao.update(session);
            return dbSession.getId();
        }
        dao.create(session);
        sessions = dao.queryBuilder()
                .where()
                .eq("number", session.getName())
                .query();
        if (sessions.isEmpty()) {
            return -1;
        } else {
            session = (Session) sessions.get(0);
            return session.getId();
        }
    }
    @SneakyThrows
    public void saveSms(Sms sms){
        Integer sessionId = saveSession(sms);
        sms.setSessionId(sessionId);
        Dao dao = getDao(Sms.class);
        dao.create(sms);
    }

}
